const bcrypt = require("bcryptjs");
const { sequelize } = require("../../core/db");
const { Sequelize, Model } = require("sequelize");

// 定义管理员模型
class Admin extends Model {
  static async verifyEmailPassword(account, plainPassword) {
    // 查询管理员
    const admin = await Admin.findOne({
      where: {
        account,
      },
    });

    if (!admin) {
      throw new global.errs.AuthFailed("账号不存在");
    }

    // 验证密码
    const correct = bcrypt.compareSync(plainPassword, admin.password);

    if (!correct) {
      throw new global.errs.AuthFailed("密码不正确");
    }

    return admin;
  }
}

// 初始管理员模型
Admin.init(
  {
    admin_id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    admin_name: Sequelize.STRING,
    power: {
      type: Sequelize.INTEGER,
      defaultValue: 16,
    },

    account: Sequelize.STRING,
    status: {
      type: Sequelize.ENUM("active", "inactive", "banned"),
      allowNull: false,
      defaultValue: "active",
      comment: "用户状态",
    },
    phone: Sequelize.STRING,
    inviteCode: {
      type: Sequelize.STRING,
    },

    avatar: {
      type: Sequelize.STRING,
      defaultValue:
        "https://cdn.cellsplus.top/images/2024-08-13/1723554346314.png",
    },
    area: Sequelize.STRING,
    email: {
      type: Sequelize.STRING(128),
      unique: true,
    },
    password: {
      // 扩展 设计模式 观察者模式
      // ES6 Reflect Vue3.0
      type: Sequelize.STRING,
      set(val) {
        // 加密
        const salt = bcrypt.genSaltSync(10);
        // 生成加密密码
        const psw = bcrypt.hashSync(val, salt);
        this.setDataValue("password", psw);
      },
    },
  },
  {
    sequelize,
    tableName: "admin",
  }
);

module.exports = {
  Admin,
};
